import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getTimestamp } from './auth'
import router from '@/router'
function isTimeout() {
  const duration = 60 * 60 * 2 * 1000
  return Date.now() - getTimestamp() > duration
}
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  if (store.getters.token) {
    if (isTimeout()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token 超时'))
    }
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, err => {
  return Promise.reject(err)
})

// 响应拦截器
service.interceptors.response.use(
  res => {
    // 1.网络成功情况
    // console.log(res)
    const { success, message, data } = res.data
    if (success) {
      // 数据成功
      return data
    } else {
      // 数据失败
      Message.error(message)
      // 报错不往下执行
      return Promise.reject(new Error(message))
    }
  },
  // 2.网络失败情况
  err => {
    if (err.response && err.response.data && err.response.data.code === 10002) {
      store.dispatch('user/logout')
      router.push('/login')
    }
    // console.dir(err);
    Message.error(err.message)
    // 不让res.data.data继续往下执行
    return Promise.reject(err)
  }
)

export default service
